<?php

namespace common\models\service;

use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\TransformApi;
use common\helpers\WeChatApi;
use common\models\Campus;
use common\models\Running;
use common\models\System;
use common\models\User;
use common\models\Water;
use common\models\Withdrawal;
use yii\helpers\ArrayHelper;

class WithdrawalService extends Withdrawal
{
    /**
     * 后台列表
     * @param $fund_type
     * @return array|string
     */
    public static function backList($fund_type,$campus_id='')
    {
        $ba = new BaseController();
        $ba->model = self::className();
        if ($fund_type){
            $where['fund_type'] = $fund_type;
        }
        if ($campus_id){
            $where['campus_id'] = $campus_id;
        }
        $data = $ba->actionIndex(true,$where);
        $review_status = DictCache::get('review_status');
        $ithdraw_way = DictCache::get('withdraw_way');
        $userids = array_unique(ArrayHelper::getColumn($data['data'], 'userid'));
        $userInfo = (new User())->getUserHtml($userids);
        $campus_ids = array_unique(ArrayHelper::getColumn($data['data'], 'campus_id'));
        $campus = (new Campus)->getCampusName($campus_ids);
        foreach ($data['data'] as &$datum){
            $datum['review_status_title'] = $review_status[$datum['review_status']]??'';
            $datum['way_title'] = $ithdraw_way[$datum['way']]??'';
            $datum['user_html'] = $userInfo[$datum['userid']]??'';
            $datum['payment_amount'] = $datum['amount']-$datum['fee'];
            $datum['campus_name'] = '';
            if ($datum['campus_id']){
                $datum['campus_name'] = $campus[$datum['campus_id']]??'';
            }
        }
        return $data;
    }

    /**
     * 审核
     * @param $post
     * @return array
     */
    public static function review($post)
    {
        if (\Yii::$app->request->isGet){
            $id = \Yii::$app->request->get('id','');
            $model = Withdrawal::findOne($id);
            if (!$model){
                $back = new BaseController();
                return $back->bError('参数错误');
            }
            $review_status = DictCache::get('review_status');
            $withdraw_way = DictCache::get('withdraw_way');
            $info = $model->toArray();
            $userHtml = (new User())->getUserHtml($info['userid']);
            $info['collection_info'] = $info['collection_info']?json_decode($info['collection_info'],true):[];
            $info['way_title'] = $withdraw_way[$info['way']]??'';
            $info['payment_amount'] = $info['amount']-$info['fee'];
            $info['campus_name'] = '';
            if ($info['campus_id']){
                $info['campus_name'] = Campus::find()->where(['id'=>$info['campus_id']])->select(['name'])->scalar();
            }
            unset($review_status[0]);
            return ['model'=>$info,'review_status'=>$review_status,'userHtml'=>$userHtml[$info['userid']]??''];
        }
        if (empty($post['id'])){
            return commonApi::message('请选择要审核的记录',false);
        }
        if (empty($post['review_status'])){
            return commonApi::message('请选择审核状态',false);
        }
        $model = self::findOne($post['id']);
        if ($model->review_status!==0){
            return commonApi::message('请勿重复审核',false);
        }
        $callback_info = '';
        $user = null;
        if ($model->fund_type==1){//跑腿佣金
            $user = Running::findOne(['userid'=>$model->userid]);
        }elseif ($model->fund_type==2){//分销佣金
            $user = User::findOne(['id'=>$model->userid]);
        }else{
            return commonApi::message('完善佣金操作',false);
        }
        if (!$user){
            return commonApi::message('用户不存在',false);
        }
        $front = 0;
        if ($post['review_status']==1){
            if ($model->way==2){//企业付款到零钱
                $config = System::pay();
                $desc = $model->fund_type==1?'跑腿提现':'分销提现';
                $openid = User::find()->where(['id'=>$model->userid])->select(['openid'])->scalar();
                $user->already_brokerage += $model->amount;
                $payment_amount = $model->amount-$model->fee;
                $res = (new WeChatApi($config))->transferToBalance($model->orderid,$openid,$payment_amount,$desc.'-'.$model->orderid);
                if (!$res['success']){
                    return $res;
                }
                $callback_info = json_encode($res['data']);
            }else{
                $front = $user->can_brokerage;
                $user->can_brokerage += $model->amount;
            }
        }

        $model->review_status = $post['review_status'];
        $model->review_time = date('Y-m-d H:i:s');
        $model->review_remarks = $post['review_remarks']??'';
        $model->callback_info = $callback_info;
        TransformApi::tx(function ()use ($model,$user,$front){
            if ($model->save()&&$user->save()){
                if ($model->review_status==2){
                    Water::add($model->userid,$model->fund_type,1,$front,$model->amount,"提现审核拒绝，退还金额-【{$model->orderid}】",'');
                }
                return commonApi::message('审核成功');
            }
            throw new \Exception('审核失败');
        },$result);
        return $result;
    }
}